package com.efounder.chat.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.model.SecretFileBean;
import com.efounder.chat.utils.AESSecretUtil;
import com.efounder.chat.utils.FileEditTimeUtil;
import com.efounder.chat.utils.FileSizeUtil;
import com.efounder.chat.utils.FileTypeIconUtil;
import com.efounder.chat.utils.FileUtil;
import com.efounder.chat.utils.RSAUtil;
import com.efounder.pansoft.chat.input.SecretInputView;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileIOUtils;
import com.utilcode.util.FileUtils;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.pansoft.chat.input.ChatInputView.REQUEST_CODE_FILE;

/**
 * 密文
 */
public class SecretFileActivity extends BaseActivity implements View.OnClickListener {
    public static final int SECRET_FILE_RESULT_CODE = 2515;
    private RecyclerView mRecyclerView;
    private ImageView mIvBack;
    private TextView mTvSend;
    private EditText mEtPassword;
    private ImageView mIvShowPassword;
    private LinearLayout mSelectButton;
    private boolean showPassword;
    private CommonAdapter<Object> commonAdapter;
    private String passwordString;
    private ArrayList<Object> fileItemList;
    private ImageView mIvDeleteFile;
    private TextView mTvFileTime;
    private StubObject mStubObject;
    private Hashtable mHashtable;
    private String mToUserId;

    private Bundle mBundle;
    private String publicKey;
    private String RSAPublicKey;
    private String secretPwd;
    private Disposable encreptDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_wechat_activity_secret_file);
        initView();
        initData();
        fileItemList = new ArrayList<>();
        adapterLoadData(fileItemList);
    }

    private void initData() {
        mBundle = getIntent().getExtras();
        mStubObject = (StubObject) mBundle.getSerializable("stubObject");
        mHashtable = mStubObject.getStubTable();
        mToUserId = (String) mHashtable.get("toUserId");

        OpenEthRequest.getUserEthByImUserId(this, Integer.valueOf(mToUserId), new OpenEthRequest.EthRequestListener() {
            @Override
            public void onSuccess(String ethAddress, String publicKey1, String RSAPublicKey1) {
                publicKey = publicKey1;
                RSAPublicKey = RSAPublicKey1;
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(SecretFileActivity.this, ResStringUtil.getString(R.string.wrchatview_get_key_fail));
            }
        });
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_secret_file);
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mTvSend = (TextView) findViewById(R.id.tv_send);
        mEtPassword = (EditText) findViewById(R.id.et_password);
        mIvShowPassword = (ImageView) findViewById(R.id.iv_show_password);
        mSelectButton = (LinearLayout) findViewById(R.id.bt_select_pic);
        mIvDeleteFile = (ImageView) findViewById(R.id.iv_delete_file);
        mTvFileTime = (TextView) findViewById(R.id.tv_file_time);
        mIvBack.setOnClickListener(this);
        mTvSend.setOnClickListener(this);
        mIvShowPassword.setOnClickListener(this);
        mSelectButton.setOnClickListener(this);
        mIvShowPassword.setImageResource(R.drawable.icon_hide_password);
//        mEtPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //TODO 判断密码长度不能超过16个字符，弃用
//                String s = charSequence.toString();
//                if (s.length() >= 1) {
//                    String substring = s.substring(0, s.length() - 1);
//                    if (charSequence.length() == 17) {
//                        Toast.makeText(SecretFileActivity.this, "密码长度不能超过16个字符", Toast.LENGTH_SHORT).show();
//                        mEtPassword.setText(substring);
//                        mEtPassword.setSelection(substring.length());
//                        passwordString = substring;
//                    } else {
//                        //不足16个字符
//                    }
//                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mEtPassword.getText().toString().contains(" ")) {
                    ToastUtils.showShort(R.string.common_text_pwd_not_be_blanket);
                    mEtPassword.setText(mEtPassword.getText().toString().trim());
                    mEtPassword.setSelection(mEtPassword.getText().toString().length());
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            KeyboardUtils.hideSoftInput(mEtPassword);
            finish();
        } else if (i == R.id.tv_send) {

            String pwd = mEtPassword.getText().toString().trim();
            if (pwd.equals("")) {
                ToastUtils.showShort(R.string.common_text_please_inputpwd);
                mEtPassword.setText("");
                mEtPassword.requestFocus();
                return;
            }
            if (fileItemList.size() == 0) {
                ToastUtil.showToast(SecretFileActivity.this, ResStringUtil.getString(R.string.wrchatview_please_add_secret_file));

                return;
            }
//            if (publicKey == null || "".equals(publicKey)) {
//                ToastUtil.showToast(SecretFileActivity.this, "公钥不能为空");
//                return;
            //          }
            if (RSAPublicKey == null || "".equals(RSAPublicKey)) {
                ToastUtil.showToast(SecretFileActivity.this, getResources().getString(R.string.secret_activity_no_publickey));
                return;
            }

            sendMessage(pwd);
        } else if (i == R.id.iv_show_password) {
            if (showPassword) {// 显示密码
                mIvShowPassword.setImageResource(R.drawable.icon_show_password);
                mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                showPassword = !showPassword;
                mEtPassword.setSelection(mEtPassword.getText().toString().trim().length());
            } else {// 隐藏密码
                mIvShowPassword.setImageResource(R.drawable.icon_hide_password);
                mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                showPassword = !showPassword;
                mEtPassword.setSelection(mEtPassword.getText().toString().trim().length());

            }
        } else if (i == R.id.bt_select_pic) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_CODE_FILE);
        }
    }

    private void adapterLoadData(ArrayList<Object> dataItem) {
        commonAdapter = new CommonAdapter<Object>(this, R.layout.item_secret_file, dataItem) {

            @Override
            protected void convert(ViewHolder holder, Object o, final int position) {
//                JSONObject monitorUser = (JSONObject) o;
//                String systemUID = null;
                SecretFileBean fileBean = (SecretFileBean) o;
                ImageView fileAvatarImageView = (ImageView) holder.getView(R.id.iv_file_avatar);
                TextView fileNameTextView = (TextView) holder.getView(R.id.tv_file_name);
                TextView fileSizeTextView = (TextView) holder.getView(R.id.tv_file_size);
                TextView fileTimeTextView = (TextView) holder.getView(R.id.tv_file_time);

                FileTypeIconUtil.setFileIconByFilePath(fileAvatarImageView, fileBean.filePath);
                fileNameTextView.setText(fileBean.fileName);
                fileSizeTextView.setText(fileBean.fileSize);
                fileTimeTextView.setText(FileEditTimeUtil.getFileEditTime(fileBean.filePath));
                ImageView fileDeleteImageView = (ImageView) holder.getView(R.id.iv_delete_file);
                fileDeleteImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        fileItemList.remove(position);
                        commonAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(commonAdapter);
//        loadData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_FILE) {
            //文件
            File file;
            String filePath;
            Uri fileUri = data.getData();
            try {
                filePath = FileUtil.getPathByUri4kitkat(this, fileUri);
                String fName = filePath.trim();
                String fileName = fName.substring(fName.lastIndexOf("/") + 1);
                String fileSize = FileSizeUtil.getAutoFileOrFilesSize(filePath);
                String fileType;
                if (null != fileName && fileName.contains(".")) {
                    if (null != fileName && fileName.contains(".")) {
                        fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                    } else {
                        fileType = "";
                    }
                } else {
                    fileType = "";
                }
                SecretFileBean secretFileBean = new SecretFileBean();
                secretFileBean.fileName = fileName;
                secretFileBean.filePath = filePath;
                secretFileBean.fileSize = fileSize;
                secretFileBean.fileType = fileType;
                fileItemList.add(secretFileBean);
                commonAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //加密后跳转ChatMessageSendManager发消息
    private void sendMessage(final String pwd) {
        encreptDisposable = Observable.create(new ObservableOnSubscribe<ArrayList<String>>() {
            @Override
            public void subscribe(ObservableEmitter<ArrayList<String>> emitter) throws Exception {
                ArrayList<String> encryptFilePathList = new ArrayList<>();
                for (Object o : fileItemList) {
                    SecretFileBean secretFileBean = (SecretFileBean) o;
                    String filePath = secretFileBean.filePath;
                    encryptFile(filePath, pwd);
                    encryptFilePathList.add(FileUtil.encryptFilePath + FileUtils.getFileName(filePath));
                }
                emitter.onNext(encryptFilePathList);
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                SecretInputView.showTcLoading(SecretFileActivity.this, ResStringUtil.getString(R.string.wrchatview_file_encryption));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ArrayList<String>>() {
            @Override
            public void accept(ArrayList<String> strings) throws Exception {
                SecretInputView.dismissTcLoading();

                // secretPwd = CertificateUtil.encrypt(pwd, publicKey);
                //todo 更改加密方式

                try {
                    secretPwd = RSAUtil.encryptByPublicKey(pwd, RSAPublicKey);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(SecretFileActivity.this, ResStringUtil.getString(R.string.wrchatview_password_fail));
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("encryptList", strings);
                intent.putExtra("password", secretPwd);
                setResult(SECRET_FILE_RESULT_CODE, intent);
                SecretInputView.dismissTcLoading();
                KeyboardUtils.hideSoftInput(mEtPassword);
                finish();

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtil.showToast(SecretFileActivity.this, ResStringUtil.getString(R.string.wrchatview_file_encryption_fail));
            }
        });
    }

    //加密文件
    private void encryptFile(String url, String pwd) {
        File file = new File(url);
        if (!file.exists() && !file.isFile()) {
            return;
        }
        AESSecretUtil aesSecretUtil = new AESSecretUtil(pwd);
        //文件转bytes后加密
        byte[] encrypt = aesSecretUtil.encrypt(FileIOUtils.readFile2BytesByStream(file));
        //加密后的bytes转文件
        File file1 = new File(FileUtil.encryptFilePath + FileUtils.getFileName(file));
        try {
            if (!file1.exists()) {
                file1.createNewFile();
            }
            FileIOUtils.writeFileFromBytesByStream(file1.getAbsolutePath(), encrypt);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (encreptDisposable != null) {
            encreptDisposable.dispose();
        }

    }
}
